from typing import List, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.task import Task
from app.schemas.task import TaskCreate, TaskUpdate
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def get_tasks(
    db: AsyncSession,
    skip: int = 0,
    limit: int = 100
) -> List[Task]:
    """获取任务列表"""
    try:
        query = select(Task).offset(skip).limit(limit)
        result = await db.execute(query)
        tasks = result.scalars().all()
        return list(tasks)
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}")
        raise

async def get_task(
    db: AsyncSession,
    task_id: int
) -> Optional[Task]:
    """获取单个任务"""
    try:
        query = select(Task).filter(Task.id == task_id)
        result = await db.execute(query)
        return result.scalar_one_or_none()
    except Exception as e:
        logger.error(f"获取任务失败: {str(e)}")
        raise

async def create_task(
    db: AsyncSession,
    task: TaskCreate
) -> Task:
    """创建新任务"""
    try:
        logger.info(f"创建任务数据: {task.dict()}")
        db_task = Task(**task.dict())
        db.add(db_task)
        await db.commit()
        await db.refresh(db_task)
        return db_task
    except Exception as e:
        logger.error(f"创建任务失败: {str(e)}")
        await db.rollback()
        raise

async def update_task(
    db: AsyncSession,
    task_id: int,
    task_update: TaskUpdate
) -> Optional[Task]:
    """更新任务"""
    try:
        query = select(Task).filter(Task.id == task_id)
        result = await db.execute(query)
        db_task = result.scalar_one_or_none()
        
        if db_task:
            update_data = task_update.dict(exclude_unset=True)
            for key, value in update_data.items():
                setattr(db_task, key, value)
            
            await db.commit()
            await db.refresh(db_task)
        
        return db_task
    except Exception as e:
        logger.error(f"更新任务失败: {str(e)}")
        await db.rollback()
        raise

async def delete_task(
    db: AsyncSession,
    task_id: int
) -> bool:
    """删除任务"""
    try:
        query = select(Task).filter(Task.id == task_id)
        result = await db.execute(query)
        db_task = result.scalar_one_or_none()
        
        if db_task:
            await db.delete(db_task)
            await db.commit()
            return True
        return False
    except Exception as e:
        logger.error(f"删除任务失败: {str(e)}")
        await db.rollback()
        raise 